<?php
/**
 *Product Controller
 *
 *@author S.Feil, T.Ziegler, M.El-Hindi <goatymail@googlemail.com>
 *27 May 2012
 *@copyright Copyright (c) 2012, S.Feil, T.Ziegler, M.El-Hindi
 *@package cms
 *
 */
/**
 * Class Product_Controller
 * Administers the products
 *@package controller
 */

class Product_Controller extends Controller{
    /**
     * Holds id of page to be displayed
     * @var integer
     */
    private $iPage = '';
    /**
     * Language in wich to show page
     * @var integer
     */
    private $iLang ='';

    /**
     * Stores the template
     * @var string
     */
    private $sTemplate ='productCategories';

    /**
     * Reference to model that retrieves page data from db
     * @var object
     */
    private $oContentModel;

    /**
     * Reference to view of content section
     * @var object
     */
    private $oContentView;

    /**
     * Reference to model that retrieves page navigation elements from db
     * @var object
     */
    private $oNavigationModel;

    /**
     * Reference to view of navigation section
     * @var object
     */
    private $oNavigationView;

    /**
     * Reference to view of left navigation section in cms, it shows the entire pagestructure
     * @var object
     */
    private $oLeftNavigationView;

    /**
     * Error message which will be displayed in case of error
     * @var string
     */
    private $sError;

    public function __construct(){
        //Gets Viewmanger reference from parent constructor
        parent::__construct();
        //Loads models and views
        $this->oImageModel = Loader::loadModel('image');
        $this->oContentModel = Loader::loadModel('productPage');
        $this->oNavigationModel = Loader::loadModel('navigation');
        $this->oNavigationView = $this->oViewmanager->getView('navigation');
        $this->oLeftNavigationView = $this->oViewmanager->getView('leftnavigation');

        //Checks language set in Cookie, take default language specified in config if not set
        if (isset($_COOKIE['language'])){
            $this->iLang = intval($_COOKIE['language']);
        }else{
            $this->iLang = "1";
        }
    }
    /**
     * checks GET-Parameters forwarded from Router::route
     * @param Array $aArgs Arguments to check
     */
    public function checkArgs($aArgs){
        //Reads out the product page or category page which should be loaded
        $this->iPage = array_shift($aArgs);
        //Checks if iPage is a category page and set the template to productList
        $bIsCategory = $this->oContentModel->isCategory($this->iPage);
        if($bIsCategory){
            $this->sTemplate = 'productList';
        }
        //Loads the template which was set
        $this->oContentView = $this->oViewmanager->getView("$this->sTemplate");
        // ID is the product ID if set load the product detail template
        if (isset($aArgs['id'])){
            $iProductID = intval($aArgs['id']);
            $this->sTemplate = 'productDetail';
            $this->oContentView = $this->oViewmanager->getView("$this->sTemplate");
            $this->oContentView->assign('title', $this->oContentModel->getPageTitle($this->iPage,$this->iLang));
            $this->oContentView->assign('content', $this->oContentModel->getProductDetail($iProductID,$this->iLang));
            $this->oContentView->assign('images', $this->oContentModel->getProductImages($iProductID));
            //If it's a category load all products of the category
        }elseif($bIsCategory){
            $this->oContentView->assign('content', $this->oContentModel->getProducts($this->iPage, $this->iLang));
            //If it's neither a category or a product the product categories will be loaded
        }else{
            $this->oContentView->assign('content', $this->oContentModel->getCategories($this->iPage, $this->iLang));
            $this->oContentView->assign('productPageID', $this->iPage);
        }
         
        //Product has been edited and must be saved
        //Checks if a method is called
        if($this->iPage == 'saveProduct'){
            if (isset($aArgs['id'])){
                if(isset($_POST['mainimage'])){
                    $iMainimage = $_POST['mainimage'];
                }else{
                    $iMainimage = DEFAULT_PRODUCT_IMAGE_ID;
                }
                //Updates the database and the product will be saved
                $this->oContentModel->updateProduct($aArgs['id'], $_POST['name'], $_POST['short_description'], $_POST['long_description'],
                $iMainimage, $this->iLang);
                //Referes to the product detail page
                $url = $_SERVER['HTTP_REFERER'];
                header('Location: '.$url);
                exit();
            }
            //If a product should be deleted
        }elseif($this->iPage == 'deleteProduct'){
            if (isset($aArgs['id'])){
                $iProductCategory = $this->oContentModel->getProductAttribut($aArgs['id'], 'category');
                $aProductImages = $this->oContentModel->getProductImages($aArgs['id']);
                //Product model deletes the product from the database
                $this->oContentModel->deleteProduct($aArgs['id']);
                //Deletes every image from the filesystem which belongs to the product id
                foreach($aProductImages as $aImage){
                    $sImage="../image/".$aImage['link'];
                    $sThumbnail="../image/thumbs/".$aImage['link'];
                    if(file_exists($sImage)){
                        unlink($sImage);
                    }
                if(file_exists($sThumbnail)){
                        unlink($sThumbnail);
                    }
                }
                //Refers to the location to the product category
                header("Location: index.php?ca=product&category=$iProductCategory");
                exit();
            }
            //Deltes a single image from a product
        }elseif($this->iPage == 'deleteImage'){
            if (isset($aArgs['iid'])){
                $sImageLink = $this->oImageModel->getImageLink($aArgs['iid']);
                if($sImageLink != ''){
                    //Product Model deletes the singel image from the database
                    $this->oImageModel->deleteProductImage($aArgs['iid']);
                }
                //If file exists delte it from the filesystem
                if(file_exists($sImageLink)){
                    unlink($sImageLink);
                }
            }
            $url = $_SERVER['HTTP_REFERER'];
            header('Location: '.$url);
            exit();
            
        // Uploads a Product Image
        }elseif($this->iPage == 'uploadProductImage'){
            if (isset($aArgs['id'])){

                if(isset($_FILES['datei1'])){
                    $aImage = $_FILES['datei1'];
                    if (isset($aImage['tmp_name'])&& $aImage['tmp_name']!=""){
                        $aDateityp = GetImageSize($aImage['tmp_name']);

                        if($aDateityp[2] != 0){

                            if($aImage['size'] <  1024000){
                                $oThumbCreator = new Thumb(IMAGE_UPLOAD_PATH, THUMBNAIL_PATH);
                                $sFile = IMAGE_UPLOAD_PATH.$aImage['name'];
                                move_uploaded_file($aImage['tmp_name'], $sFile);
                                $oThumbCreator->generateThumbFile(true,$aImage['name'], $aImage['name'], 95, $aDateityp[2], THUMB_MAX_X, THUMB_MAX_Y);
                                //Passes data to the model and call a method to update data in database
                                $this->oImageModel->uploadProductImage($aArgs['id'], $aImage['name']);
                            }else{
                                echo "Das Bild darf nicht größer als 1024 kb sein";
                            }

                        }else{
                            echo "Bitte nur Bilder im gif bzw. jpg Format hochladen";
                        }
                    }
                    //Locates back to the last page 
                    $url = $_SERVER['HTTP_REFERER'];
                    header('Location: '.$url);
                    exit();
                }
            }
            // Calls when user changes position of categories
        }elseif($this->iPage == 'saveCategories'){

            $aPageStructure = $this->oContentModel->getCategories($_POST['productPageID'],$this->iLang);
            // Updates the navigation
            $this->oContentModel = Loader::loadModel('pageStructure');
            foreach($aPageStructure as $aElement){
                $iPid = $aElement['id'];
                //Passes data to the model and call a method to update data in database
                $this->oContentModel->updatePageStructure($this->iLang, $iPid, $_POST["productPageID"], $_POST["position$iPid"], $_POST["name$iPid"], $_POST["visible$iPid"]);

            }
            //Locates back to the last page 
            $url = $_SERVER['HTTP_REFERER'];
            header('Location: '.$url);
            exit();
        }
    }
/**
 * Executes controller methods
 * @param array different arguments
 */
    public function execute($aArgs){
        //Checks the arguments in the method checkArgs
        $this->checkArgs($aArgs);

        //Passes data to view
        $this->oContentView->assign('error', $this->sError);

        $this->oNavigationView->assign('contentANDproductPages', $this->oNavigationModel->getPageStructure('NULL', $this->iLang, "(type = 'contentPage' OR type = 'product')"));
        $this->oNavigationView->assign('products', $this->oNavigationModel->getPagesByTyp('', $this->iLang, 'product'));
        $this->oNavigationView->assign('categories', $this->oNavigationModel->getPagesByTyp('', $this->iLang, 'category'));
        $this->oLeftNavigationView->assign('leftnavigation', $this->oNavigationModel->getPageStructure('NULL', $this->iLang));

        //Inserts data in the correct sections of the website layout
        $this->oViewmanager->setSection('Title', $this->oContentModel->getPageTitle($this->iPage,$this->iLang));
        $this->oViewmanager->setSection('Content', $this->oContentView->display());
        $this->oViewmanager->setSection('LeftNavigation', $this->oLeftNavigationView->display());
        $this->oViewmanager->setSection('Navigation', $this->oNavigationView->display());
    }
    //Ajax function which updates the product structure
    public function updateProductStructure($aProductOrderPost){
        $sProductOrder = $aProductOrderPost['updSort'];
        $aProductOrder = explode(",",$sProductOrder);
        //Passes data to the model and call a method to update data in database
        $this->oContentModel->updateProductStructure($aProductOrder);
    }

}
